package edu.nyu.hps.assignment10;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Main {

	/**
	 * @param args
	 */
	@SuppressWarnings("null")
	public static void main(String[] args) {
		int port = 4444, player = 0, time = 0, board[][] = null, constraints[] = null;
		boolean connected = false;
		String response = null;
		Socket client;

		// Socket handles
		InputStreamReader isr;
		BufferedReader in = null;
		PrintWriter out = null;

		if (args.length > 1) {
			port = Integer.parseInt(args[0]);
		}

		// Initialization
		try {
//			client = new Socket("128.122.80.195", port);
			client = new Socket("localhost", port);
			isr = new InputStreamReader(client.getInputStream());
			in = new BufferedReader(isr);
			out = new PrintWriter(client.getOutputStream(), true);

			while (!connected) {
				response = null;
				out.println("JOIN:Hiral");

				// Waiting for the ACK or NACK responses from the server
				while ((response = in.readLine()) == null) {
				}

				if (response.charAt(0) == 'A') {
					System.out.println("ACK message is " + response);
					player = Integer.parseInt(response.split(":")[1]);
					connected = true;
				}
			}
			Sudoku game = new Sudoku();

			while (true) {
				while ((response = in.readLine()) == null) {
				}
				String[] input = response.split(":");
				if (input[0].equalsIgnoreCase("STATUS")) {
					System.out.println(response);
					break;
				}

				if (input[0].equals("PLAY")) {
//					System.out.println(response);
					
					//parsing time
					time = Integer.parseInt(input[1]);
					
					board = new int[9][9];
					constraints = new int[2];
					//parsing board
					String[] rows = input[2].split(";");
					for (int i = 0; i < rows.length; i++) {
						String[] columns = rows[i].split(",");
						for (int j = 0; j < columns.length; j++) {
							board[i][j] = Integer.parseInt(columns[j]);
						}
					}
					
					//parsing constraints
					constraints[0] = Integer.parseInt(input[3].split(",")[0]);
					constraints[1] = Integer.parseInt(input[3].split(",")[1]);
				}
				
				game.board  = board.clone();
				game.constraints = constraints.clone();
//				System.out.println("The board I have is: ");
//				for(int i=0;i<game.board.length;i++) {
//					for(int j=0;j<game.board[i].length;j++) {
//						System.out.print(board[i][j] + " : ");
//					}
//				}
				String ans = game.play();
				System.out.print(ans);
				out.println(ans);
			}

		} catch (Exception e) {
			System.out.println("Could not get I/O");
		}

	}
}